package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"repo-master1/cache"
	"repo-master1/models"
	"strconv"
	"time"
)

func AddOrder(c *gin.Context) {
	bid, _ := strconv.Atoi(c.PostForm("bid"))
	money, _ := strconv.Atoi(c.PostForm("money"))
	order_code, _ := strconv.Atoi(c.PostForm("order_code"))
	if bid == 0 || money == 0 || order_code == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	order := models.Order{
		Bid:       bid,
		Money:     money,
		OrderCode: order_code,
	}

	err := models.DB.Create(&order).Error

	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ListOrder(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var order []models.Order

	redis_key := "List_Order_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}

	var total int64
	models.DB.Model(&order).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "添加成功",
		"data":  order,
		"total": total,
	})
	return
}

func FindOrder(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "数据不能为空",
		})
		return
	}

	var order models.Order

	redis_key := "Find_Order_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": order,
	})
	return
}
